/*
 * utils.cpp
 * 串口调试工具 - 通用工具函数源文件
 * 
 * 此文件包含Utils命名空间下的通用工具函数实现，包括字节大小格式化、
 * 时间戳生成、数据传输速率计算、十六进制转换等功能。
 */

#include "utils.h"
#include <QDateTime>
#include <QRegularExpression>
#include <QStringBuilder>
#include <qdebug.h>
#include <QRandomGenerator>

namespace Utils {

// 格式化字节大小
QString formatByteSize(quint64 bytes)
{
    const char *suffixes[] = {"B", "KB", "MB", "GB"};
    int suffixIndex = 0;
    double size = bytes;
    
    while (size >= 1024.0 && suffixIndex < 3) {
        size /= 1024.0;
        suffixIndex++;
    }
    
    return QString::number(size, 'f', 2) % " " % suffixes[suffixIndex];
}

// 生成时间戳
QString generateTimestamp(const QString &format)
{
    return QDateTime::currentDateTime().toString(format.isEmpty() ? "yyyy-MM-dd HH:mm:ss.zzz" : format);
}

// 生成日志时间戳
QString generateLogTimestamp()
{
    return QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
}

// 计算数据传输速率（字节/秒）
double calculateTransferRate(quint64 bytes, qint64 milliseconds)
{
    if (milliseconds <= 0) {
        return 0.0;
    }
    
    return (bytes * 1000.0) / milliseconds;
}

// 格式化传输速率
QString formatTransferRate(double bytesPerSecond)
{
    const char *suffixes[] = {"B/s", "KB/s", "MB/s", "GB/s"};
    int suffixIndex = 0;
    double rate = bytesPerSecond;
    
    while (rate >= 1024.0 && suffixIndex < 3) {
        rate /= 1024.0;
        suffixIndex++;
    }
    
    return QString::number(rate, 'f', 2) % " " % suffixes[suffixIndex];
}

// 转换字节数组为十六进制字符串
QString bytesToHexString(const QByteArray &bytes, bool addSpaceBetweenBytes)
{
    if (bytes.isEmpty()) {
        return QString();
    }
    
    if (addSpaceBetweenBytes) {
        return bytes.toHex(' ');
    } else {
        return bytes.toHex();
    }
}

// 转换十六进制字符串为字节数组
QByteArray hexStringToBytes(const QString &hexString)
{
    // 移除所有非十六进制字符
    QString cleanHex = hexString;
    cleanHex.remove(QRegularExpression("[^0-9a-fA-F]"));
    
    // 确保字符串长度为偶数
    if (cleanHex.length() % 2 != 0) {
        cleanHex += "0";
    }
    
    return QByteArray::fromHex(cleanHex.toUtf8());
}

// 验证十六进制字符串
bool isValidHexString(const QString &hexString)
{
    QRegularExpression hexRegex("^[0-9a-fA-F\\s]*$");
    return hexRegex.match(hexString).hasMatch();
}

// 替换字符串中的转义序列
QString replaceEscapeSequences(const QString &text)
{
    QString result = text;
    
    // 替换常见的转义序列
    result.replace("\\r", "\r");
    result.replace("\\n", "\n");
    result.replace("\\t", "\t");
    result.replace("\\\"", "\"");
    result.replace("\\'", "\'");
    result.replace("\\\\", "\\");
    
    // 处理\xHH格式的十六进制转义序列
    QRegularExpression hexEscapeRegex("\\\\x([0-9a-fA-F]{2})");
    QRegularExpressionMatchIterator it = hexEscapeRegex.globalMatch(result);
    
    while (it.hasNext()) {
        QRegularExpressionMatch match = it.next();
        QString hexValue = match.captured(1);
        bool ok;
        uchar byteValue = hexValue.toUInt(&ok, 16);
        
        if (ok) {
            result.replace(match.capturedStart(), match.capturedLength(), QChar(byteValue));
        }
    }
    
    return result;
}

// 计算CRC16校验值
quint16 calculateCRC16(const QByteArray &data, quint16 polynomial, quint16 initialValue, bool finalXor)
{
    quint16 crc = initialValue;
    
    for (int i = 0; i < data.size(); ++i) {
        crc ^= static_cast<quint8>(data.at(i)) << 8;
        
        for (int j = 0; j < 8; ++j) {
            if (crc & 0x8000) {
                crc = (crc << 1) ^ polynomial;
            } else {
                crc = crc << 1;
            }
        }
    }
    
    if (finalXor) {
        crc ^= 0xFFFF;
    }
    
    return crc;
}

// 计算常用的Modbus CRC16
quint16 calculateModbusCRC16(const QByteArray &data)
{
    return calculateCRC16(data, 0xA001, 0xFFFF, false);
}

// 生成校验和（8位）
quint8 calculateChecksum8(const QByteArray &data, bool twoComplement)
{
    quint8 sum = 0;
    
    for (int i = 0; i < data.size(); ++i) {
        sum += static_cast<quint8>(data.at(i));
    }
    
    if (twoComplement) {
        return static_cast<quint8>(~sum + 1);
    }
    
    return sum;
}

// 生成校验和（16位）
quint16 calculateChecksum16(const QByteArray &data, bool twoComplement)
{
    quint16 sum = 0;
    
    for (int i = 0; i < data.size(); ++i) {
        sum += static_cast<quint8>(data.at(i));
    }
    
    if (twoComplement) {
        return static_cast<quint16>(~sum + 1);
    }
    
    return sum;
}

// 格式化字节为ASCII（不可打印字符显示为.）
QString formatAsciiString(const QByteArray &data)
{
    QString result;
    
    for (int i = 0; i < data.size(); ++i) {
        uchar byte = static_cast<uchar>(data.at(i));
        if (byte >= 32 && byte <= 126) {
            result += QChar(byte);
        } else {
            result += '.';
        }
    }
    
    return result;
}

// 格式化字节数组为十六进制和ASCII的组合视图（类似hexdump）
QString formatHexDump(const QByteArray &data, int bytesPerLine)
{
    if (data.isEmpty()) {
        return QString();
    }
    
    QString result;
    int lineCount = (data.size() + bytesPerLine - 1) / bytesPerLine;
    
    for (int line = 0; line < lineCount; ++line) {
        // 添加偏移量
        QString offset = QString("%1: ").arg(line * bytesPerLine, 8, 16, QLatin1Char('0'));
        result += offset;
        
        // 添加十六进制数据
        QString hexData;
        QString asciiData;
        
        for (int i = 0; i < bytesPerLine; ++i) {
            int index = line * bytesPerLine + i;
            if (index < data.size()) {
                uchar byte = static_cast<uchar>(data.at(index));
                hexData += QString("%1 ").arg(byte, 2, 16, QLatin1Char('0'));
                
                // 添加ASCII字符
                if (byte >= 32 && byte <= 126) {
                    asciiData += QChar(byte);
                } else {
                    asciiData += '.';
                }
            } else {
                hexData += "   ";
                asciiData += ' ';
            }
        }
        
        result += hexData + " | " + asciiData + "\n";
    }
    
    return result;
}

// 生成随机数据
QByteArray generateRandomData(int length)
{
    QByteArray data;
    data.resize(length);
    
    for (int i = 0; i < length; ++i) {
        data[i] = static_cast<char>(QRandomGenerator::global()->bounded(256));
    }
    
    return data;
}

// 将字符串分割成固定长度的块
QStringList splitStringIntoChunks(const QString &text, int chunkSize)
{
    QStringList chunks;
    
    for (int i = 0; i < text.size(); i += chunkSize) {
        chunks << text.mid(i, chunkSize);
    }
    
    return chunks;
}

// 合并字符串列表，添加分隔符
QString joinStringsWithSeparator(const QStringList &strings, const QString &separator)
{
    return strings.join(separator);
}

// 提取文本中的所有数字
QStringList extractNumbers(const QString &text)
{
    QStringList numbers;
    QRegularExpression numberRegex("\\d+");
    QRegularExpressionMatchIterator it = numberRegex.globalMatch(text);
    
    while (it.hasNext()) {
        QRegularExpressionMatch match = it.next();
        numbers << match.captured(0);
    }
    
    return numbers;
}

// 从文件名中提取扩展名
QString extractFileExtension(const QString &filename)
{
    int dotIndex = filename.lastIndexOf('.');
    if (dotIndex != -1 && dotIndex < filename.length() - 1) {
        return filename.mid(dotIndex + 1).toLower();
    }
    return QString();
}

// 验证IP地址格式
bool isValidIpAddress(const QString &ipAddress)
{
    QRegularExpression ipRegex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    return ipRegex.match(ipAddress).hasMatch();
}

// 验证端口号范围
bool isValidPortNumber(quint16 port)
{
    return (port > 0 && port <= 65535);
}

// 将整数转换为二进制字符串
QString intToBinaryString(int value, int bits)
{
    QString result = QString::number(value, 2);
    
    // 补零到指定位数
    if (result.length() < bits) {
        result = result.rightJustified(bits, '0');
    }
    
    return result;
}

// 解析版本字符串（格式：x.y.z）
QVector<int> parseVersionString(const QString &version)
{
    QVector<int> components;
    QStringList parts = version.split('.');
    
    for (const QString &part : parts) {
        bool ok;
        int value = part.toInt(&ok);
        if (ok) {
            components << value;
        }
    }
    
    return components;
}

// 比较版本字符串
int compareVersionStrings(const QString &version1, const QString &version2)
{
    QVector<int> v1 = parseVersionString(version1);
    QVector<int> v2 = parseVersionString(version2);
    
    int minLength = qMin(v1.size(), v2.size());
    
    for (int i = 0; i < minLength; ++i) {
        if (v1[i] < v2[i]) {
            return -1;
        } else if (v1[i] > v2[i]) {
            return 1;
        }
    }
    
    // 版本前缀相同，比较长度
    if (v1.size() < v2.size()) {
        return -1;
    } else if (v1.size() > v2.size()) {
        return 1;
    }
    
    // 版本相同
    return 0;
}

} // namespace Utils